<template>
  <div
    class="login page-find-password"
    :style="backgroundImage"
  >
    <div class="login-box">
      <div class="top">
        <div class="logo">
          <img
            :src="checkFileUrl(configuration.bsLoginLogoImg)"
            style="max-height: 45px;max-width: 174px;"
            alt
          >
          <span class="login-title">{{ configuration.bsTitleContent }}</span>
        </div>
      </div>
      <div class="mid">
        <el-form
          v-if="statu === '1'"
          ref="dataFormRef"
          :model="dataForm"
          :rules="dataRule"
          @submit.prevent
          @keyup.enter="onSubmit()"
        >
          <el-form-item prop="mobile">
            <div class="mobile-box">
              <div class="mobile-int">
                <el-input
                  v-model="dataForm.mobile"
                  class="info"
                  type="text"
                  maxlength="11"
                  :placeholder="$t('distribution.phoneNum')"
                >
                  <template #append>
                    <div
                      v-if="show"
                      class="get-code-btn"
                      @click="geCode()"
                    >
                      {{ $t('shop.getVerificationCode') }}
                    </div>
                    <div
                      v-else
                      class="get-code-btn"
                    >
                      {{ count }} s
                    </div>
                  </template>
                </el-input>
              </div>
            </div>
          </el-form-item>
          <el-form-item prop="validCode">
            <el-input
              v-model="dataForm.validCode"
              class="info"
              type="text"
              maxlength="6"
              :placeholder="$t('home.verificationCode')"
            />
          </el-form-item>
          <el-form-item>
            <div class="btn-box">
              <div
                class="item-btn default-btn primary-btn"
                @click="findPwdNext()"
              >
                {{ $t('product.nextStep2') }}
              </div>
              <div class="bottom-row">
                <div class="to-login">
                  {{ $t('homes.alreadyAccount') }}？<span
                    class="default-btn text-btn"
                    @click="toLogin"
                  >{{ $t('homes.goToLogin') }}</span>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <el-form
          v-if="statu === '2'"
          ref="dataFormRef"
          :model="dataForm"
          :rules="dataRule"
          @submit.prevent
          @keyup.enter="onSubmit()"
        >
          <el-form-item
            prop="password"
            class="password"
          >
            <el-input
              v-model="dataForm.password"
              v-input-rule
              class="info"
              maxlength="20"
              type="password"
              :placeholder="$t('sys.password')"
            />
          </el-form-item>
          <el-form-item prop="valPassword">
            <el-input
              v-model="dataForm.valPassword"
              v-input-rule
              class="info"
              maxlength="20"
              type="password"
              :placeholder="$t('sys.confirmPassword')"
            />
          </el-form-item>
          <el-form-item>
            <div class="btn-box">
              <div
                class="item-btn default-btn primary-btn"
                @click="onSubmit()"
              >
                {{ $t('sys.confirmUpdate') }}
              </div>
              <div class="bottom-row">
                <div class="to-login">
                  {{ $t('homes.alreadyAccount') }}？
                  <span
                    class="default-btn text-btn"
                    @click="toLogin"
                  >
                    {{ $t('homes.goToLogin') }}
                  </span>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="bottom">
        {{ configuration.bsCopyright }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { isMobile } from '@/utils/validate.js'
import { encrypt } from '@/utils/crypto.js'
import { formatConfigInfo } from '@/utils/website-config.js'
import { ElMessage } from 'element-plus'
import { validPassword } from '@/utils/validate'

const route = useRoute()
const router = useRouter()

const dataForm = reactive({
  password: '',
  mobile: '',
  valPassword: '',
  validCode: ''
})
// 背景样式
const backgroundImage = reactive({
  width: '100%',
  height: '100%',
  backgroundSize: '100% 100%',
  position: 'fixed',
  top: 0
})

const configuration = ref({
  bsLoginLogoImg: null,
  bsLoginBgImg: null,
  bsCopyright: null,
  bsTitleContent: null,
  bsTitleImg: null,
  bsMenuTitleOpen: null,
  bsMenuTitleClose: null
})

const validateMobile = (rule, value, callback) => {
  if (!isMobile(value)) {
    callback(new Error($t('homes.InputCorrectPhone')))
  } else {
    callback()
  }
}
const validatePassword = (rule, value, callback) => {
  if (validPassword(value)) {
    callback()
  } else {
    callback(new Error($t('passwordVerification')))
  }
}
const validateValPassword = (rule, value, callback) => {
  if (value !== dataForm.password) {
    callback(new Error($t('homes.istrue')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  password: [
    { required: true, message: $t('home.pawNoNull'), trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  valPassword: [
    { required: true, message: $t('home.pawNoNull'), trigger: 'blur' },
    { validator: validateValPassword, trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: $t('sys.mobilePhoneNoNull'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ],
  validCode: [
    { required: true, message: $t('home.capNoNull'), trigger: 'blur' }
  ]
})

onMounted(() => {
  getWebConfigData()
})

const dataFormRef = ref(null)
let hadGotCode = false
// 验证码相关
const show = ref(true)
const count = ref('')
let timer = null
const statu = ref('1')
/**
 * 获取验证码
 */
const geCode = () => {
  if (!dataForm.mobile || !isMobile(dataForm.mobile)) {
    dataFormRef.value?.validateField('mobile')
    return
  }
  if (hadGotCode) {
    return
  }
  // 判断值
  hadGotCode = true
  http({
    url: http.adornUrl('/shop/shopUserRegister/sendUpdatePwdCode'),
    method: 'post',
    data: http.adornData({
      mobile: dataForm.mobile,
      shopAccount: 1 // 是否店铺账号： 1是
    })
  }).then(() => {
    const timeCount = 60
    if (!timer) {
      count.value = timeCount
      show.value = false
      timer = setInterval(() => {
        if (count.value > 0 && count.value <= timeCount) {
          count.value--
        } else {
          show.value = true
          clearInterval(timer)
          timer = null
          hadGotCode = false
        }
      }, 1000)
    }
  }).catch(() => {
    hadGotCode = false
  })
}

let checkRegisterSmsFlag = ''
const findPwdNext = () => {
  dataFormRef.value?.validate(() => {
    route.query.t = '2'
    http({
      url: http.adornUrl('/shop/shopUserRegister/checkUpdatePwdSms'),
      method: 'PUT',
      data: http.adornData({
        mobile: dataForm.mobile,
        validCode: dataForm.validCode
      })
    }).then(({ data }) => {
      checkRegisterSmsFlag = data
      statu.value = '2'
    }).catch(() => {
    })
  })
}

let isSubmit = false
// 提交表单
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (isSubmit) {
        return
      }
      if (dataForm.valPassword === null || dataForm.valPassword === '') {
        ElMessage.error($t('sys.confirmPassNoNull'))
        isSubmit = false
        return
      }
      if (dataForm.valPassword !== dataForm.password) {
        ElMessage.error($t('sys.passworldContrast'))
        isSubmit = false
        return
      }
      isSubmit = true
      http({
        url: http.adornUrl('/shop/shopUserRegister/updatePwd'),
        method: 'PUT',
        data: http.adornData({
          password: encrypt(dataForm.password),
          mobile: dataForm.mobile,
          validCode: dataForm.validCode,
          checkRegisterSmsFlag
        })
      }).then(() => {
        ElMessage({
          type: 'success',
          message: $t('resource.updateSuccess'),
          duration: 1500,
          onClose: () => {
            isSubmit = false
            nextTick(() => {
              router.push('/login')
            })
          }
        })
      }).catch(() => {
        isSubmit = false
      })
    }
  })
}

const webConfig = useWebConfigStore()
// 获取网站配置信息
const getWebConfigData = () => {
  http({
    url: http.adornUrl('/sys/webConfig/getActivity'),
    method: 'get'
  }).then(({ data }) => {
    data = formatConfigInfo(data)
    webConfig.addData(data)
    configuration.value = data
    backgroundImage.backgroundImage = 'url(' + checkFileUrl(data.bsLoginBgImg) + ')'
  })
}

// 去注册
const toLogin = () => {
  router.push({ path: '/login' })
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
